﻿using System;
using System.Collections.Generic;
using System.Xml;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;
using Ro.AssistFunction.BackNodeInfo;
using Ro.AssistFunction.OutputManage;
using Ro.Common.RoArgs;
using Ro.Common.RoInterface.RoWebAction;
using Ro.Common.RoInterface.UserType;
using Ro.DriverEvent.FindElement;

namespace Ro.DriverEvent.WebAction
{
    /// <summary>
    /// 浏览器操作
    /// </summary>
    public class WebBrowser : IWebBrowserFunc
    {
        /// <summary>
        /// 浏览器回退
        /// 回退至前一个页面
        /// </summary>
        /// <param name="sigNode">BrowserBack节点</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserBack(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;

            try
            {
                //当前句柄
                string firsttab = RoTestObject.WebTestObject.CurrentWindowHandle;
                //后退
                RoTestObject.WebTestObject.Navigate().Back();
                //再次获取当前句柄
                string secondtab = RoTestObject.WebTestObject.CurrentWindowHandle;
                //如果回退与前一个页面句柄相同，或直接回退至new tabs 
                if (secondtab == firsttab && RoTestObject.WebTestObject.Title == "New Tab")
                {
                    back = BackActionResult.BackWebResult(false, "未使用", "没有回退成功，或直接回退至新的tab标签页"); //结果
                }
                else
                {
                    back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
                }
            }
            //抛出异常
            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserBack操作遭遇异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserBack", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器页面（tab）关闭
        /// </summary>
        /// <param name="sigNode">WebBrowserClose节点</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserCloseTab(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;
            try
            {
                //关闭页面
                //所有的窗口句柄
                IList<string> handles = RoTestObject.WebTestObject.WindowHandles;
                string firsthandle = handles[0];
                //当前句柄
                string tab1 = RoTestObject.WebTestObject.CurrentWindowHandle;

                //执行关闭
                RoTestObject.WebTestObject.Close();
                RoTestObject.WebTestObject.SwitchTo().Window(firsthandle);

                string tab2 = RoTestObject.WebTestObject.CurrentWindowHandle;
                //验证
                if (tab1 == tab2 && tab2 == null && RoTestObject.WebTestObject.Title == "New Tab")
                {
                    back = BackActionResult.BackWebResult(false, "未使用", "Tab标签没有关闭成功或直接关闭进入到了新标签页"); //结果
                }
                else
                {
                    back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
                }
            }
            //抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserCloseTab操作遭遇异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserCloseTab", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器关闭窗口
        /// </summary>
        /// <param name="sigNode">WebBrowserClose</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserClose(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;
            try
            {
                //关闭浏览器
                RoTestObject.WebTestObject.Quit();
                if (RoTestObject.WebTestObject.ToString().Contains("null"))
                {
                    back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
                }
                else
                {
                    back = BackActionResult.BackWebResult(false, "未使用", "浏览器关闭没有成功"); //结果 
                }
            }
            //抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserClose相关操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserClose", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器执行JavaScript脚本
        /// </summary>
        /// <param name="sigNode">WebBrowserExecuteScript</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserExecuteScript(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();
            try
            {
                //获取js代码
                string jscode = extractNeedInfo.ExtractInnerText(sigNode, "web:JavaScript");
                IJavaScriptExecutor jsExecutor = RoTestObject.WebTestObject as IJavaScriptExecutor;
                jsExecutor?.ExecuteScript(jscode);
                back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
            }

            //抛出异常

            catch (Exception e)
            {
                back.Result = false;
                back.ControlId = "未使用";
                back.ExtraInfo = "Browser相关操作遭遇System异常";
                ExceptionOutPut.SystemExceptionOut("WebBrowserExecuteScript", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器前进
        /// </summary>
        /// <param name="sigNode">WebBrowserForward</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserForward(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            try
            {
                //当前句柄
                string tab1 = RoTestObject.WebTestObject.CurrentWindowHandle;
                //后退
                RoTestObject.WebTestObject.Navigate().Forward();
                //再次获取当前句柄
                string tab2 = RoTestObject.WebTestObject.CurrentWindowHandle;

                if (tab2 == tab1 && RoTestObject.WebTestObject.Title == "New Tab")
                {
                    back.Result = false;
                    back.ControlId = "未使用";
                    back.ExtraInfo = "浏览器前进未成功或直接进入了新标签页";
                }
                back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
            }

            //抛出异常

            catch (Exception e)
            {
                back.Result = false;
                back.ControlId = "未使用";
                back.ExtraInfo = "Browser相关操作遭遇System异常";
                ExceptionOutPut.SystemExceptionOut("WebBrowserForward", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器进入某网址
        /// </summary>
        /// <param name="sigNode">WebBrowserGoToUrl</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserGoToUrl(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();

            //提取超时
            TimeSpan timeout = extractNeedInfo.ExtractTimeout(sigNode);
            //获取url
            string url = extractNeedInfo.ExtractInnerText(sigNode, "web:Url");
            try
            {
                //设置超时
                RoTestObject.WebTestObject.Manage().Timeouts().PageLoad = timeout;
                //执行载入


                RoTestObject.WebTestObject.Navigate().GoToUrl(url);
                back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
            }
            //抛出异常

            catch (Exception e)
            {
                back.Result = false;
                back.ControlId = "未使用";
                back.ExtraInfo = "Browser相关操作遭遇System异常";
                ExceptionOutPut.SystemExceptionOut("WebBrowserGoToUrl", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器刷新
        /// </summary>
        /// <param name="sigNode">WebBrowserRefresh</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserRefresh(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();

            //提取超时
            TimeSpan timeout = extractNeedInfo.ExtractTimeout(sigNode);
            try
            {
                //设置超时
                RoTestObject.WebTestObject.Manage().Timeouts().PageLoad = timeout;
                //执行载入
                RoTestObject.WebTestObject.Navigate().Refresh();
                back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
            }
            // 抛出异常

            catch (Exception e)
            {
                back.Result = false;
                back.ControlId = "未使用";
                back.ExtraInfo = "Browser相关操作遭遇System异常";
                ExceptionOutPut.SystemExceptionOut("WebBrowserRefresh", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器强制停止刷新
        /// </summary>
        /// <param name="sigNode">WebBrowserStop</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserStop(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;
            try
            {
                //更改为js
                IJavaScriptExecutor jsExecutor = RoTestObject.WebTestObject as IJavaScriptExecutor;
                jsExecutor?.ExecuteScript("window.stop();");
                //验证状态
                string com = (string) jsExecutor?.ExecuteScript("return document.readyState");
                if (com == "complete")
                {
                    back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
                }
                else
                {
                    back = BackActionResult.BackWebResult(false, "未使用", "浏览器无法停止刷新"); //结果
                }
            }

            // 抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserStop相关操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserStop", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器切换Frame
        /// </summary>
        /// <param name="sigNode">WebBrowserSwitchFrame</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserSwitchFrame(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            //初始化   
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();

            //切换类型
            string changetype = sigNode.FirstChild.Name;

            //提取超时
            TimeSpan timeout = extractNeedInfo.ExtractTimeout(sigNode);

            //提取元素
            string value = extractNeedInfo.ExtractAttributeValue(sigNode, "web:RoWebElementID");

            //获取webelement
            FindWebElement findWebElement = new FindWebElement(value, timeout);
            IWebElement ele = findWebElement.WebElement;

            try
            {
                switch (changetype)
                {
                    //切换到原Frame
                    case "web:BackToOld":
                        //同时更改测试对象
                        RoTestObject.WebTestObject = RoTestObject.WebTestObject.SwitchTo().DefaultContent();
                        back = BackActionResult.BackWebResult(true, value, "切换Frame成功"); //结果
                        break;

                    //切换到新Frame
                    case "web:GetToNew":

                        if (ele != null)
                        {
                            //同时更改测试对象
                            RoTestObject.WebTestObject = RoTestObject.WebTestObject.SwitchTo().Frame(ele);
                            back = BackActionResult.BackWebResult(true, value, "切换Frame成功"); //结果
                            break;
                        }
                        back = BackActionResult.BackWebResult(false, value, "浏览器切换IFrame时遭遇查找元素失败，获取元素为null"); //结果
                        break;
                }
            }
            // 抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, value, "WebBrowserSwitchFrame相关操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserSwitchFrame", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器切换窗口(Tab)
        /// </summary>
        /// <param name="sigNode">WebBrowserSwitchToTab</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserSwitchToTab(XmlNode sigNode)
        {
            //返回值
            WebActionResult back = new WebActionResult();
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();
            //提取元素
            string value = extractNeedInfo.ExtractInnerText(sigNode, "web:TabName");
            try
            {
                //所有的窗口句柄
                IList<string> handles = RoTestObject.WebTestObject.WindowHandles;
                //当前的窗口句柄
                string nowhandles = RoTestObject.WebTestObject.CurrentWindowHandle;
                //执行切换
                foreach (string sinhandles in handles)
                {
                    if (sinhandles.Equals(nowhandles)) continue;
                    RoTestObject.WebTestObject.SwitchTo().Window(sinhandles);
                    if (RoTestObject.WebTestObject.Title.Contains(value))
                    {
                        back = BackActionResult.BackWebResult(true, "未使用", "没有附加信息"); //结果
                    }
                    else
                    {
                        back = BackActionResult.BackWebResult(false, "未使用", "浏览器切换Tab标签失败"); //结果
                
                    }
                }
            }
            // 抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserSwitchToTab相关操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserSwitchToTab", e);
            }
            return back;
        }



        /// <summary>
        /// 浏览器截图
        /// </summary>
        /// <param name="sigNode">WebBrowserTakeSnapshot</param>
        /// <returns>返回是否完成</returns>
        public WebActionResult WebBrowserTakeSnapshot(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();
            //提取元素
            string value = extractNeedInfo.ExtractInnerText(sigNode, "web:ImageFile");
            try
            {
                //获取路径和名称
                string imagepath = RoPubArgments.TempLogInfo.ImageFolderPath + "/" + value;
                //浏览器截图
                RoTestObject.WebTestObject.TakeScreenshot().SaveAsFile(imagepath, ScreenshotImageFormat.Jpeg);
                back = BackActionResult.BackWebResult(true, "未使用", "浏览器截图成功，图片路径：" + imagepath); //结果
            }
            // 抛出异常

            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(false, "未使用", "WebBrowserTakeSnapshot相关操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebBrowserTakeSnapshot", e);
            }
            return back;
        }
    }
}